package com.zhiyou.app.shop.website.util;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;

import com.zhiyou.app.shop.common.util.Page;

public class SiteUtil {

	/**
	 * @param orderMap
	 * @return
	 */
	public static void addOrderToCriteria(Criteria cri , Order ... orders) {
		if(null != orders){
			for(Order o : orders){
				cri.addOrder(o);
			}
		}
	}
	
	/**
	 * @param page
	 * @param cri
	 */
	public static void setPageProperties(Page page, Criteria cri){
		
		if(page == null) return;
		
		
		/*获取总记录数开始*/
		Integer totalCountObject = ((Long)cri.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		
		int totalCount  = totalCountObject ==null ? 0 :totalCountObject.intValue();
		
		page.setTotalCount(totalCount);
		/*获取总记录数结束*/	
		
		cri.setProjection(null);
		
		cri.setFirstResult(page.getOffset()).setMaxResults(page.getPageSize());
	}
	
	public static void setPageTotalCountOnly(Session session,Page page, DetachedCriteria dCri){
		Criteria cri = dCri.getExecutableCriteria(session);
		setPageProperties(page, cri);
	}
}
